package com.znyj.cloud.chain.dispatch;

import com.znyj.cloud.chain.dispatch.annotation.UrlDispatcherMapping;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gaoliwei on 15-2-9.
 */
@Component
public class SimpleUrlHandlerMapping extends AbstractAnnotationHandlerMapping {

    @Override
    protected List<HandlerExecution> resolveExecutionChain(Object executor) {
        List<HandlerExecution> handlerExecutions = new ArrayList<>();

        //非null判断
        if (null == executor) {
            return handlerExecutions;
        }

        Method[] methods = ReflectionUtils.getAllDeclaredMethods(executor.getClass());

        for (Method method : methods) {
            if (!method.isAnnotationPresent(UrlDispatcherMapping.class)) {
                continue;
            }
            UrlDispatcherMapping urlDispatcherMapping = method.getAnnotation(UrlDispatcherMapping.class);
            //从注解中获取url
            String patchUri = getPatcherValue(urlDispatcherMapping);
            //增加execution
            HandlerExecution handlerExecution = new HandlerExecution(executor, method, patchUri);
            handlerExecutions.add(handlerExecution);
        }

        return handlerExecutions;
    }

    private String getPatcherValue(UrlDispatcherMapping annotation) {
        String uri = annotation.value();
        return uri;
    }

    public Object execute(ChannelHandlerContext ctx, HttpRequest msg) {
        String uri = msg.getUri();
        if (uri.contains("?")) {
            uri = uri.substring(0, uri.indexOf("?"));
        }
        return execute(uri, ctx, msg);
    }

}
